package com.itheima.service.impl;

import com.itheima.mapper.PermissionMapper;
import com.itheima.mapper.RoleMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Result;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;//角色

    @Autowired
    private PermissionMapper permission;//权限

    @Override
    public User findUserByUserName(String username) {
        //调用方法查询用户
        User user = userMapper.findUserByUserName(username);
        //判断用户是否为空
        if (user == null) {
            //表是没有查到该用户
            return null;
        }

        //System.out.println("用户的id是:"+user.getId());

        //该用户存在,查询用户所对应的角色和相关权限
        Set<Role> roleSet = roleMapper.findRolesByUserId(user.getId());//得到该用户的所有角色存到集合
        //遍历集合
        for (Role role : roleSet) {
            //获取当前角色对象,根据经角色的id储存相关的权限
            Set<Permission> permissionSet = permission.findPermissionsByRoleId(role.getId());
            //将获取的集合存到当前角色中
            role.setPermissions(permissionSet);
        }
        //将获取角色集合赋值给当前用户
        user.setRoles(roleSet);

        //返回当前用户
        return user;
    }

}
